import gradio as gr
from PIL import Image
from modelscope_studio import encode_image, decode_image, call_demo_service
import json
import os
from skimage import io

style_dict = {"日漫风":"anime", "3D风":"3d", "手绘风":"handdrawn", "素描风":"sketch", "艺术效果":"artstyle"}

def get_size(h, w, max = 720):
    if min(h, w) > max:
        if h > w:
            h, w = int(max * h / w), max
        else:
            h, w = max, int(max * w / h)
    return h, w

def inference(image: Image, style: str) -> Image:

    style = style_dict[style]

    w, h = image.size
    h, w = get_size(h, w, 720)

    image = image.resize((w, h))

    input_url = encode_image(image)

    data = {
        "task": "image-portrait-stylization",
        "inputs": [
            input_url
        ],
        "urlPaths": {
            "inUrls": [
                {
                    "value": input_url,
                    "fileType": "png",
                    "type": "image",
                    "displayType": "ImgUpload",
                    "displayProps": {
                        "label": {
                            "text": "原图",
                            "style": {
                                "background": "rgba(98,74,255,0.8)",
                                "color": "#fff"
                            }
                        }
                    },
                    "validator": {
                        "max_resolution": "3000*3000",
                        "max_size": "10M"
                    },
                    "name": "",
                    "title": ""
                }
            ],
            "outUrls": [
                {
                    "outputKey": "output_img",
                    "type": "image",
                }
            ]
        }
    }
    if style == "anime":
        style = ""
    else:
        style = "-"+style
    model_id = 'cv_unet_person-image-cartoon'+style+'_compound-models'
    result = call_demo_service(path='damo', name=model_id,
                                       data=json.dumps(data))
    print(result)
    res_url = result['data']['output_img']

    res_img = io.imread(res_url)



    return res_img


css_style = "#fixed_size_img {height: 240px;} "


title = "AI人像多风格漫画"
# description = "输入一张人像照片,并指定希望的风格（如：日漫风、3D风、手绘风、素描风、艺术效果），内置多种风格模型用于生成对应的转换结果。本页面提供了在线体验的服务，欢迎使用！"
description = '''
街拍，人像，团建照片...随意上传您心仪的照片，选择对应风格(日漫风，3D风，手绘风等等)，一键即可转换为不同风格的卡通化图片！多风格的人像模型已经内置好，点点鼠标就可以抢占朋友圈的C位，立刻玩起来吧
'''
examples = [[os.path.dirname(__file__) + './images/input1.png'], [os.path.dirname(__file__) + './images/input2.png'], [os.path.dirname(__file__) + './images/input3.png'], [os.path.dirname(__file__) + './images/input4.png']]
# examples = [[os.path.dirname(__file__) + '/images/input1.png'], [os.path.dirname(__file__) + '/images/input2.png'], [os.path.dirname(__file__) + '/images/input3.png']]

with gr.Blocks(title=title, css=css_style) as demo:
    
    gr.HTML('''
      <div style="text-align: center; max-width: 720px; margin: 0 auto;">
                  <div
                    style="
                      display: inline-flex;
                      align-items: center;
                      gap: 0.8rem;
                      font-size: 1.75rem;
                    "
                  >
                    <h1 style="font-family:  PingFangSC; font-weight: 500; line-height: 1.5em; font-size: 32px; margin-bottom: 7px;">
                      AI人像多风格漫画
                    </h1>
                  </div>
                  <img id="overview" alt="overview" src="https://modelscope.oss-cn-beijing.aliyuncs.com/demo/image-cartoon/demo_sin1.gif" />
                  
                </div>
      ''')


    gr.Markdown(description)
    with gr.Row():
        radio_style = gr.Radio(label="风格选择", choices=["日漫风", "3D风", "手绘风", "素描风", "艺术效果"], value="日漫风")
    with gr.Row():
        img_input = gr.Image(type="pil", elem_id="fixed_size_img")
        img_output = gr.Image(type="pil", elem_id="fixed_size_img")
    with gr.Row():
        btn_submit = gr.Button(value="一键生成", elem_id="blue_btn")
        # btn_clear = gr.Button(value="清除")

    examples = gr.Examples(examples=examples, inputs=[img_input], outputs=img_output)
    btn_submit.click(inference, inputs=[img_input, radio_style], outputs=img_output)
    # btn_clear清除画布


demo.launch()